const Router = require('koa-router')
const md5 = require('md5')
const UserModel = require('../models/user')

const route = new Router({ prefix: '/user' })

// 登录
route.post('/login', async (ctx) => {
    const { username, pwd } = ctx.request.body
    let data = {
        isLogin: false,
        msg: '',
        title: 'xxx博客'
    }
    try {
        // 查询数据库
        let user = await UserModel.findOne({ username })
        if (user && user.pwd === md5(md5(pwd))) {
            // 登录成功
            ctx.session.user = true
            await ctx.redirect('/')
        } else {
            data.msg = '用户名或密码错误'
            // 登录失败
            await ctx.render('login', data)
        }
    } catch (error) {
        ctx.status = 501
        data.msg = '登录失败'
        // 登录失败
        await ctx.render('login', data)
    }
})

route.get('/logout', async ctx => {
    delete ctx.session.user
    ctx.redirect('/')
})

// 注册
route.post('/register', async (ctx) => {
    const { username, pwd } = ctx.request.body
    let result = {
        success: false,
        data: null,
        error: null,
        msg: ''
    }
    try {
        // 注册查重
        let user = await UserModel.findOne({ username })
        if (user === null) {
            await UserModel.create({
                username,
                pwd: md5(md5(pwd)),
            })
            result.success = true
        } else {
            result.error = '用户名已经存在'
        }
    } catch (error) {
        result.error = error
    }
    ctx.body = result
})

module.exports = route
